//
//  SYJComposePickerView.swift
//  weibo
//
//  Created by 孙英建 on 16/4/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

// cell重用标识
let keyPickerView = "SYJComposePickerViewItem"

class SYJComposePickerView: UICollectionView {
    
    // 数据源数组
    var imageArr: [UIImage] = [UIImage]()
    
    // 闭包告诉外界弹出相册选择控制器
    var composePickerViewClosure: (() -> ())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setUpUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // 设置UI
    private func setUpUI(){
        
        self.backgroundColor = UIColor.whiteColor()
        
        // 如果没有图片则隐藏配图
        self.hidden = true
        
        dataSource = self
        delegate = self
        
        // 注册cell
        registerClass(SYJComposePickerViewCell.self, forCellWithReuseIdentifier: keyPickerView)
        
        // 布局
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        let margin: CGFloat = 5
        let cellHW = (kWidth - 20 - 2 * margin) / 3
        
        layout.itemSize = CGSize(width: cellHW, height: cellHW)
        
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
    }
    
    
    // MARK: - 供外界调用添加图片到数据源数组的方法
    func addImageToImageArr(image: UIImage){
        // 向数组中最前边插入图片
        imageArr.insert(image, atIndex: 0)
        
        // 如果图片多于九张则删除最先插入的
        if imageArr.count > 9 {
            imageArr.removeLast()
        }
        
        if imageArr.count > 0{
            self.hidden = false
        }
        
        self.reloadData()
    }


}

// MARK: - 数据源和代理方法
extension SYJComposePickerView: UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = imageArr.count
        if count == 0 || count == 9 {
            return count
        }else{
            return count + 1
        }
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(keyPickerView, forIndexPath: indexPath) as! SYJComposePickerViewCell
        
        cell.composePickerViewCellClosure = {[weak self] in
            self?.imageArr.removeAtIndex(indexPath.item)
            if self?.imageArr.count == 0{
                self?.hidden = true
            }
            self?.reloadData()
        }
        
        if indexPath.item == imageArr.count{
            cell.image = nil
        }else{
            cell.image = imageArr[indexPath.item]
        }
        
        return cell
    }
    
    // item的点击方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 取消item的选中状态
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        composePickerViewClosure?()
    }
    
}


// MARK: - 自定义cell
class SYJComposePickerViewCell: UICollectionViewCell{
    
    // 保存item中的图片
    var image: UIImage?{
        didSet{
            if image != nil{
                bgImageView.image = image
                bgImageView.highlightedImage = nil
                deleteButton.hidden = false
            }else{
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteButton.hidden = true
            }
        }
    }
    
    // 传递点击按钮事件的闭包
    var composePickerViewCellClosure: (() -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // 设置UI控件
    private func setUpUI(){
        // 添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(deleteButton)
        
        // 添加约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.trailing.equalTo(contentView)
        }
        
        
    }
    
    // 删除按钮的点击事件
    @objc private func deleteBtnClick(){
        composePickerViewCellClosure?()
    }
    
    
    // MARK: - 懒加载控件
    
    // 相册背景图片
    private lazy var bgImageView: UIImageView = {
       let bgiv = UIImageView()
        return bgiv
    }()
    
    //删除按钮
    private lazy var deleteButton: UIButton = {
       let deleteBtn = UIButton()
        deleteBtn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        deleteBtn.addTarget(self, action: "deleteBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        return deleteBtn
    }()
    
}












